<template>
  <view class="glo-upload">
    <up-upload
      :width="`${width}rpx`"
      :height="`${height}rpx`"
      :fileList="fileList"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      multiple
      :maxCount="maxCount">
      <view
        class="upload-wrap"
        :style="{ width: width + 'rpx', height: height + 'rpx' }">
        <up-icon name="plus" color="#498CFF" size="20rpx"></up-icon>
        <sc-text :text="text" size="15" color="#3D3D3D"></sc-text>
      </view>
    </up-upload>
  </view>
</template>

<script setup>
import config from "@/commons/config.js";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  maxCount: {
    type: Number,
    default: 1,
  },
  width: {
    type: Number,
    default: 90,
  },
  height: {
    type: Number,
    default: 90,
  },
  text: {
    type: String,
    default: "点击上传",
  },
});

const emit = defineEmits(["update:modelValue", "success", "delete"]);
const syncModelValue = () => {
  emit("update:modelValue", [...fileList.value]);
};

const fileList = ref(props.modelValue);

const deletePic = (event) => {
  fileList.value.splice(event.index, 1);
  syncModelValue();
  emit("delete", event);
};

const afterRead = async (event) => {
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);
    let item = fileList.value[fileListLen];
    const data = {
      ...item,
      status: "success",
      message: "",
      url: result,
    };
    fileList.value.splice(fileListLen, 1, data);
    fileListLen++;
    syncModelValue();
    emit("success", data);
  }
};

const uploadFilePromise = (url) => {
  const accessToken = uni.$sc.storage.get("accessToken");
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: config.uploadUrl,
      filePath: url,
      name: "file",
      header: {
        Token: `Bearer ${accessToken}`,
        Authorization: `Bearer ${accessToken}`,
      },
      formData: {
        user: "test",
      },
      success: (res) => {
        setTimeout(() => {
          resolve(JSON.parse(res.data).originalUrl);
        }, 1000);
      },
    });
  });
};
</script>

<style lang="scss" scoped>
.upload-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #e7f1ff;
  gap: 10rpx;
}
</style>
